/**
 * Axios 请求封装
 */
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/modules/user'
import { apiConfig, authConfig } from '@/config'
import router from '@/router'

// 创建axios实例
const request = axios.create({
  baseURL: apiConfig.baseURL,
  timeout: apiConfig.timeout,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
})

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    // 添加token
    const token = localStorage.getItem(authConfig.tokenKey)
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    const { data } = response
    
    // 根据业务需求处理响应数据
    if (data.code === 200 || data.success === true) {
      // 成功响应，返回数据部分
      return data.data || data
    } else if (data.code === 401) {
      // token过期，跳转登录
      const userStore = useUserStore()
      userStore.logout()
      router.push('/login')
      ElMessage.error('登录已过期，请重新登录')
      return Promise.reject(new Error('登录已过期'))
    } else {
      // 业务错误
      const errorMsg = data.message || '请求失败'
      ElMessage.error(errorMsg)
      return Promise.reject(new Error(errorMsg))
    }
  },
  (error) => {
    // 网络错误处理
    let errorMsg = '网络错误'
    if (error.response) {
      const { status, data } = error.response
      switch (status) {
        case 400:
          errorMsg = data?.message || '请求参数错误'
          break
        case 401:
          errorMsg = '登录已过期'
          const userStore = useUserStore()
          userStore.logout()
          router.push('/login')
          break
        case 403:
          errorMsg = '没有权限访问'
          break
        case 404:
          errorMsg = '请求的资源不存在'
          break
        case 500:
          errorMsg = '服务器内部错误'
          break
        default:
          errorMsg = data?.message || `请求失败 (${status})`
      }
    } else if (error.code === 'ECONNABORTED') {
      errorMsg = '请求超时'
    } else if (error.message.includes('Network Error')) {
      errorMsg = '网络连接失败'
    }

    ElMessage.error(errorMsg)
    return Promise.reject(error)
  }
)

export default request